package tools

import (
	"bytes"
	"github.com/alecthomas/chroma/formatters/html"
	stats "github.com/mdigger/goldmark-stats"
	"github.com/yuin/goldmark"
	emoji "github.com/yuin/goldmark-emoji"
	highlighting "github.com/yuin/goldmark-highlighting"
	"github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/text"
)

// ToHTML 转换成HTML
func ToHTML(source string) (string, int, error) {
	// 自定义 MarkDown 解析
	md := goldmark.New(
		goldmark.WithExtensions(
			extension.GFM,
			extension.Table,
			emoji.Emoji),
		// 语法高亮
		goldmark.WithExtensions(
			highlighting.NewHighlighting(
				highlighting.WithStyle("monokai"),
				highlighting.WithFormatOptions(
					html.WithLineNumbers(true),
				),
			),
		),
	)
	var buf bytes.Buffer
	if err := md.Convert([]byte(source), &buf); err != nil {
		return "", 0, err
	}

	// 得到文本字数
	doc := goldmark.DefaultParser().Parse(text.NewReader(buf.Bytes()))
	info := stats.New(doc, buf.Bytes())

	return buf.String(), info.Chars, nil
}
